package com.liqi.web.controller.common.minio;

import com.liqi.common.core.domain.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

@Api(tags = "文件服务管理")
@RequestMapping("/minio")
@RestController
public class MinIoController {

    @Autowired(required = false)
    private MinIoService minIoService;

    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        List<String> validImageFormats = Arrays.asList("jpg", "jpeg", "png", "gif");
        List<String> validZipFormats = Arrays.asList("zip");
        if (validImageFormats.contains(fileExtension) || validZipFormats.contains(fileExtension)) {
            return R.ok(minIoService.upload(file));
        } else {
            return R.fail("无效的文件格式。只允许上传图片（jpg、jpeg、png、gif）和压缩文件（zip）");
        }
    }

    @ApiOperation("文件下载")
    @GetMapping("/download")
    public void download(String fileName, HttpServletResponse response) {
        minIoService.download(fileName, response);
    }

    @ApiOperation("文件删除")
    @PostMapping("/delete")
    public R deleteFile(String fileName) {
        minIoService.deleteFile(fileName);
        return R.ok();
    }

}
